package com.pac.weixin.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.common.tools.MD5Tools;
import com.common.tools.StringTools;
import com.common.tools.TimeTools;
import com.common.util.ErrorNumber;
import com.common.util.LogicException;
import com.common.util.PropertyUtils;
import com.kuanrf.commons.weixin.api.WxService;
import com.kuanrf.commons.weixin.exception.WxErrorException;
import com.kuanrf.commons.weixin.msg.bean.result.WxOAuth2AccessToken;
import com.kuanrf.commons.weixin.msg.bean.result.WxUser;
import com.pac.file.bean.FileBean;
import com.pac.file.service.FileService;
import com.pac.questionnaire.QuestionnaireKeyContent;
import com.pac.questionnaire.bean.QuestionnaireBean;
import com.pac.questionnaire.service.QuestionnaireService;
import com.pac.user.bean.UserBean;
import com.pac.user.service.UserService;
import com.pac.weixin.bean.WxChatBean;
import com.pac.weixin.bean.WxDoctorSelBean;
import com.pac.weixin.bean.WxUserBean;
import com.pac.weixin.service.WeiXinService;
import com.pac.weixin.service.WxChatService;
import com.pac.weixin.service.WxDoctorSelService;
import com.pac.weixin.service.WxUserService;

/**
 * 微信service实现
 * 
 * @author lujun.chen
 * @version [版本号, 2015年2月25日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Service(value = "weiXinService")
public class WeiXinServiceImpl implements WeiXinService {

	private static Logger logger = Logger.getLogger(WeiXinServiceImpl.class);

	@Autowired
	private WxChatService wxChatService;

	@Autowired
	private WxDoctorSelService wxDoctorSelService;

	@Autowired
	private UserService userService;

	@Autowired
	private FileService fileService;

	@Autowired
	private WxUserService wxUserService;

	@Autowired
	private WxService wxMpService;

	@Autowired
	private QuestionnaireService questionnaireService;

	@Override
	public boolean selDoctor(String userId, String nickname, String openid,
			String hospitalId) {

		String title = "病史问卷";
		String questionnaireUrl = "questionnaire01";
		String qusetionnaireId = QuestionnaireKeyContent.QUESTIONNAIRE_ID_RETURN_VIEW;
		if (!StringUtils.isEmpty(hospitalId)) {
			QuestionnaireBean questionnairnQ = new QuestionnaireBean();
			questionnairnQ.setHospitalId(hospitalId);
			questionnairnQ
					.setAutoSend(QuestionnaireKeyContent.QUESTIONNAIRE_AUTO_SEND_NO);
			List<QuestionnaireBean> questionnaireList = questionnaireService
					.queryQuestionnaire(questionnairnQ);
			if ((null != questionnaireList) && (!questionnaireList.isEmpty())) {
				for (QuestionnaireBean questionnaireR : questionnaireList) {
					if (!qusetionnaireId.equals(questionnaireR.getId())) {
						questionnaireUrl = "questionnaire";
						qusetionnaireId = questionnaireR.getId();
					}
					sendQuestionnaire(nickname, questionnaireUrl, openid,
							userId, questionnaireR.getTitle(), qusetionnaireId);
				}
			} else {
				sendQuestionnaire(nickname, questionnaireUrl, openid, userId,
						title, qusetionnaireId);
			}
		} else {
			sendQuestionnaire(nickname, questionnaireUrl, openid, userId,
					title, qusetionnaireId);
		}

		// 保存选择医生记录
		WxDoctorSelBean wxDoctorSelBean = new WxDoctorSelBean();
		wxDoctorSelBean.setOpenId(openid);
		wxDoctorSelBean.setUserId(userId);
		return wxDoctorSelService.addWxDoctorSel(wxDoctorSelBean);
	}

	/**
	 * 选择医生发送文件
	 * 
	 * @param nickname
	 * @param questionnaireUrl
	 * @param openid
	 * @param userId
	 * @param title
	 * @param qusetionnaireId
	 * @see [类、类#方法、类#成员]
	 */
	private void sendQuestionnaire(String nickname, String questionnaireUrl,
			String openid, String userId, String title, String qusetionnaireId) {
		// 给微信用户发送提示信息
		try {

			String domain = PropertyUtils.getValue("system.domain.url");
			StringBuffer sbContent = new StringBuffer();
			sbContent.append("【" + nickname + "】：");
			sbContent.append("请完成如下问卷以便详细了解您的病史，");
			sbContent.append("<a href='");
			sbContent.append(domain);
			sbContent.append("/weixin/qusetionnaire/gotoPage?pageName=");
			sbContent.append(questionnaireUrl);
			sbContent.append("&");
			sbContent.append("openId=" + openid);
			sbContent.append("&");
			sbContent.append("qusetionnaireId=" + qusetionnaireId);
			sbContent.append("'>");
			sbContent.append(title);
			sbContent.append("</a>");

			WxChatBean wxChatBean = new WxChatBean();
			wxChatBean.setContent(sbContent.toString());
			wxChatBean.setOpenId(openid);
			wxChatBean.setUserId(userId);
			wxChatService.addChatFromPac(wxChatBean);
		} catch (Exception ex) {
			logger.error("选择医生给微信用户发送提示消息出错，" + ex);
		}
	}

	@Override
	public boolean wxUserinfo(WxOAuth2AccessToken autoToken) {
		WxUser wxUser = new WxUser();
		try {
			wxUser = wxMpService.oauth2getUserInfo(autoToken, null);
		} catch (WxErrorException e) {
			throw new LogicException(ErrorNumber.ERROR_MESSAGE,
					"获取微信用户信息移除，请稍后再试");
		}

		// 头像保存在自己的服务器
		String headimgUrl = wxUser.getHeadImgUrl();
		try {
			if (!StringTools.isNull(headimgUrl)) {
				String path = "headimg/" + TimeTools.now("yyyy") + "/"
						+ TimeTools.now("MM") + "/" + TimeTools.now("dd");
				FileBean fileBean = fileService.uploadFile(headimgUrl, path);
				headimgUrl = fileBean.getPath();
			} else {
				String domain = PropertyUtils.getValue("system.domain.url");
				headimgUrl = domain + "/images/header/system_header.png";
			}

		} catch (Exception ex) {
			logger.error("下载微信头像放到本地服务器出错，" + ex);
		}

		UserBean userBean = new UserBean();
		userBean.setHeadImg(headimgUrl);
		userBean.setNickname(wxUser.getNickname());
		userBean.setUserName(wxUser.getOpenId());
		userBean.setPassword(MD5Tools.MD5(wxUser.getOpenId()));

		// 没有该用户就新增
		UserBean userQ = new UserBean();
		userQ.setUserName(wxUser.getOpenId());
		UserBean userR = userService.findUser(userQ);
		if (null == userR) {
			userService.addUser(userBean);

			// 完事微信用户信息
			WxUserBean wxUserBean = new WxUserBean();
			wxUserBean.setOpenid(wxUser.getOpenId());
			wxUserBean.setNickname(wxUser.getNickname());
			wxUserBean.setSex(String.valueOf(wxUser.getSexId()));
			wxUserBean.setProvince(wxUser.getProvince());
			wxUserBean.setCity(wxUser.getCity());
			wxUserBean.setCountry(wxUser.getCountry());
			wxUserBean.setHeadimgurl(wxUser.getHeadImgUrl());
			wxUserService.updateWxUser(wxUserBean);

		} else {

			// 有了就修改
			userBean.setId(userR.getId());
			userService.editUserBase(userBean);
		}

		return true;
	}

}
